package com.example.basestationforballonproject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.basestationforballonproject.exceptions.StringIsNotAPhoneNumberException;
import com.example.basestationforballonproject.utils.AlertHelper;
import com.example.basestationforballonproject.utils.ExternalStorageFileWriter;
import com.example.basestationforballonproject.utils.SharedPreferencesManager;
import com.example.basestationforballonproject.utils.SmsSender;

public class MainActivity extends Activity {

	private SmsSender sender;
	public static final String LOG_TAG = "ballonBase";
	public static final String TEXT_SEPERATOR = "|";

	private Spinner componentSpinner;
	private Spinner actionSpinner;
	private TextView phoneNumberEditText;

	private String selectedComponent;
	private String selectedAction;
	private boolean componentIsSelected = false;
	private boolean actionIsSelected = false;

	private SharedPreferencesManager sharedPreferencesManager;

	private Intent baseStationIntent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		sharedPreferencesManager = new SharedPreferencesManager(MainActivity.this);
		phoneNumberEditText = (TextView) findViewById(R.id.phoneNumberEditText);
		phoneNumberEditText.setText(sharedPreferencesManager.getString(SharedPreferencesManager.KEY_PHONE_NUMBER));

		sender = new SmsSender(MainActivity.this);

		componentSpinner = (Spinner)findViewById(R.id.spinnerComponent);
		actionSpinner = (Spinner)findViewById(R.id.spinnerAction);
		addListenersToSpinners();

		componentSpinner.setFocusableInTouchMode(true);
		componentSpinner.requestFocus();	
		
		baseStationIntent = new Intent(MainActivity.this, BaseStationService.class);
		startService(baseStationIntent);
	}
	
	//TODO onServiceDestroy

	public void onSendButtonClicked(View v) {
		if(componentIsSelected && actionIsSelected) {
			String phoneNumberFromEditText = String.valueOf(phoneNumberEditText.getText());
			String joinedMessage = this.selectedComponent.substring(0, 3) + TEXT_SEPERATOR + this.selectedAction;
			
			try {
				sender.sendSMS(phoneNumberFromEditText, joinedMessage);
				BaseStationService.logger.fileLog("Trying to send SMS to " + phoneNumberFromEditText + "\n" + joinedMessage);
				AlertHelper.getDialog("SMS out", "Your SMS is now about to be sent - check the log for a delivery report or error message", MainActivity.this).show();
			} catch (StringIsNotAPhoneNumberException e) {
				Toast.makeText(getApplicationContext(), e.getMessage() + " " + phoneNumberFromEditText, Toast.LENGTH_LONG).show();
				Log.d(LOG_TAG, e.getMessage());
			}
		}
		else {
			Toast.makeText(getApplicationContext(), "Not all input fields are filled out", Toast.LENGTH_LONG).show();
			Log.d(LOG_TAG, "not all input fields are filled out");
		}
	}

	public void onAsDefaultButtonClicked(View v) {
		sharedPreferencesManager.putString(SharedPreferencesManager.KEY_PHONE_NUMBER, String.valueOf(phoneNumberEditText.getText()));
		Toast.makeText(getApplicationContext(), "The number was set as default", Toast.LENGTH_LONG).show();
	}

	public void addListenersToSpinners() {
		componentSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				selectedComponent = parent.getItemAtPosition(pos).toString();
				if(selectedComponent.equals(parent.getItemAtPosition(0).toString()))
					componentIsSelected = false;
				else
					componentIsSelected = true;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}

		});

		actionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				selectedAction = parent.getItemAtPosition(pos).toString();
				if(selectedAction.equals(parent.getItemAtPosition(0).toString()))
					actionIsSelected = false;
				else
					actionIsSelected = true;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;
	}

	@SuppressWarnings("deprecation")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_info:
			AlertHelper.getDialog("Log", "All sent commands are logged in a file on the external storage.\n\n Filename:\n "+ExternalStorageFileWriter.FILE_NAME, this).show();
			return true;
			
		case R.id.action_destroy_service:
			final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();

			alertDialog.setTitle("Exit");
			alertDialog.setMessage("The Service will now be destroyed and the activity too. SMS delivery reports will no longer be logged");

			alertDialog.setButton("Got it", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					
					stopService(baseStationIntent);
					alertDialog.cancel();
					
					finish();
					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.addCategory(Intent.CATEGORY_HOME);
//					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}
			});

			alertDialog.setCancelable(true);
			
			alertDialog.show();
			return true;
			
		case R.id.action_delete_log:
			if(BaseStationService.logger.removeFile())
				Toast.makeText(getApplicationContext(), "Log file deleted", Toast.LENGTH_LONG).show();
			else
				Toast.makeText(getApplicationContext(), "Log file NOT deleted", Toast.LENGTH_LONG).show();
			
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}
}